using Microsoft.AspNetCore.Mvc;
using EmployeeApi.Dto;
using EmployeeApi.Models;
using EmployeeApi.Interfaces;
using EmployeeApi.Common;

namespace EmployeeApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class EmployeeController : ControllerBase
{
    private readonly IRepository<Employee> _empRep;
    public EmployeeController(IRepository<Employee> empRep)
    {
        _empRep = empRep;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var list = await _empRep.GetAllAsync();
        if (list.Count == 0)
        {
            return Ok(ApiResponse<string>.Fail(1004, "暂无数据"));
        }
        return Ok(ApiResponse<List<Employee>>.Success(list));
    }

    [HttpPost]
    public async Task<IActionResult> GetAdd(EmployeeDto employeeDto)
    {
        var employee = new Employee { EmpName = employeeDto.EmpName, Age = employeeDto.Age };
        await _empRep.AddAsync(employee);
        return Ok(ApiResponse<Employee>.Success(employee));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Edit(int id, EmployeeDto employeeDto)
    {
        var employee = await _empRep.GetByIdAsync(id);
        if (employee == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无此人,修改失败"));
        }
        employee.EmpName = employeeDto.EmpName;
        employee.Age = employeeDto.Age;
        await _empRep.UpdateAsync(employee);
        return Ok(ApiResponse<Employee>.Success(employee));
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Del(int id)
    {
        var employee = await _empRep.GetByIdAsync(id);
        if (employee == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无此人,修改失败"));
        }
        await _empRep.DeleteAsync(employee);
        return Ok(ApiResponse<Employee>.Success(employee));
    }

}